import 'dart:io';

import 'package:base_flutter/base_flutter.dart';

// import 'package:dart_ping/dart_ping.dart';
// import 'package:dart_ping_ios/dart_ping_ios.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/login/page/user_manager.dart';
import 'package:ls_work/net/api/http_api.dart';
import 'package:ls_work/sql/AppDbUtils.dart';
import 'package:ls_work/sql/protral/patrol_task_point_entity.dart';
import 'package:ls_work/viewmodel/patrol/offline_task_upload_service.dart';

import '../../message/message_config.dart';
import '../../model/patrol/patrol_task_model.dart';
import '../../res/colors.dart';
import '../../sql/protral/offline_submit_patrol_entity.dart';

class OfflineSubmitPatrolTaskViewModel extends BaseViewModel {
  OfflineSubmitPatrolTaskViewModel(BuildContext context, {required this.code})
      : super(context);
  final String code;

  var patrolHandleStatus = "正常";
  var patrolHandleStatusId = "2";

  PatrolTaskPointData? detailData;

  var detailList = <PatrolTaskPointData>[];

  var fileStringLit = <String>[];

  String feedback = '';

  var model = PatrolTaskModel();

  var hasNet = true;

  var netTips = "";

  Widget selectHandleStatusWidget() {
    var items = <PickerDataWithIdModel>[
      PickerDataWithIdModel(pickName: '正常', pickId: '2'),
      PickerDataWithIdModel(pickName: '异常', pickId: '3')
    ];
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: items.map((e) {
        return CommonText(e.pickName,
                textColor:
                    e.name == patrolHandleStatus ? Colors.white : Colors.black)
            .addToContainer(
                padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                decoration: BoxDecoration(
                    borderRadius: 5.borderRadius,
                    color: e.name == patrolHandleStatus
                        ? Colours.app_main
                        : Colors.white,
                    border: Border.all(
                        width: 1,
                        color: e.name == patrolHandleStatus
                            ? Colours.app_main
                            : Colors.grey)))
            .onTap(() {
          patrolHandleStatus = e.name;
          patrolHandleStatusId = e.pickId!;
          notifyListeners();
        });
      }).toList(),
    );
  }

  Future<void> submitPatrol() async {
    BuildConfig.isDebug;
    showLoadingDialog(msg: '提交中...');
    var _format = [
      'yyyy',
      '-',
      'mm',
      '-',
      'dd',
      ' ',
      'HH',
      ':',
      'nn',
      ':',
      'ss'
    ];
    try {
      detailData?.feedback = feedback;
      detailData?.status = 1;
      detailData?.resultStatus = patrolHandleStatusId.toInt();
      detailData?.resultStatusName = patrolHandleStatus;
      detailData?.executeDate = DateTime.now().toDateStr(_format);
      detailData?.executeByName = UserManager.userName;
      await AppDbUtils.instance().patrolTaskDao.updateTaskPoint(detailData!);
      var record = OfflineSubmitPatrolData.fromJson(detailData!.toJson());
      await AppDbUtils.instance().patrolTaskDao.saveLocalRecord(record);
      hideDialog();
      sendMessage(SendMessageEvent(MessageConfig.REFRESH_PATROL));
      notifyListeners();
      var uploadResult = await OfflineTaskUploadService.instance()
          .uploadSingleLocalRecord(record);
      if (uploadResult['success']) {
        showToast("提交成功");
      } else {
        showToast(uploadResult['msg']);
      }
      sendMessage(SendMessageEvent(MessageConfig.REFRESH_LOCAL_PATROL));
    } catch (e) {
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
      sendMessage(SendMessageEvent(MessageConfig.REFRESH_LOCAL_PATROL));
    }
  }

  // Ping? ping;
  //
  // void pingServer(){
  //   if(Platform.isIOS){
  //     DartPingIOS.register();
  //   }
  //   var host = HttpApi.baseUrl.replaceAll("https://", "").replaceAll("http://", "")
  //   .replaceAll("/ophApi/", "").split(":").first;
  //   ping = Ping(host,);
  //   showToast(host);
  //   ping!.stream.listen((event) {
  //     if(!mounted){
  //       return;
  //     }
  //     if(event==null){
  //       return;
  //     }
  //     if(event.error!=null){
  //       hasNet = false;
  //       netTips = "无法连接到服务器，本次提交将会保存在本地，后续可在本地巡防记录中上传";
  //       notifyListeners();
  //     }else{
  //       hasNet = true;
  //       if(event.response!.time!.inMilliseconds>200){
  //         netTips = "当前连接服务器延时较高";
  //       }else{
  //         netTips = "";
  //       }
  //       notifyListeners();
  //     }
  //   });
  //
  // }

  Future<void> getCodeData() async {
    showLoadingState();
    try {
      var localTaskPoint = await model.searchTaskPointByQrcode(code);
      detailList = localTaskPoint;
      detailData = detailList[0];
      showContent();
    } catch (e) {
      print(e);
      showErrorState(NetErrorUtils.getNetError(e));
    }
  }

  void changeDetail() {
    var list = detailList
        .map((e) => PickerDataWithIdModel(
              pickName: e.patrolName,
            ))
        .toList();
    DataPickerView(context, list, onSubmitListener: (p1, p2, p3) {
      detailData = detailList[p1];
      notifyListeners();
    }).show();
  }

  @override
  void onCreated() {
    super.onCreated();
    getCodeData();
    // pingServer();
    // getNetStatus();
  }

  @override
  void dispose() {
    // ping?.stop();
    super.dispose();
  }
}
